package com.ansatsing.privateProtocol.codec;

import com.ansatsing.privateProtocol.util.MarshallingCodecFactory;
import io.netty.buffer.ByteBuf;
import org.jboss.marshalling.Marshaller;

import java.io.IOException;

public class MarshallingEncoder {
    private Marshaller marshaller;
    private final byte[] LENGTH_PLACEHOLDER = new byte[4];
    public MarshallingEncoder() throws IOException {
        marshaller = MarshallingCodecFactory.buildMarshalling();
    }
    protected void encode(Object msg, ByteBuf out) throws IOException {
        try{
            int lengthPos = out.writerIndex();
            out.writeBytes(LENGTH_PLACEHOLDER);
            ChannelBufferByteOutput output = new ChannelBufferByteOutput(out);
            marshaller.start(output);
            marshaller.writeObject(msg);
            marshaller.finish();
            out.setInt(lengthPos,out.writerIndex()-lengthPos-4);
        }finally {
            marshaller.close();
        }

    }
}
